package delivery.order.service.config;


import delivery.order.service.constant.PathConstant;
import org.jodconverter.core.office.OfficeManager;
import org.jodconverter.local.office.LocalOfficeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 组件地址
 * <a href="https://zh-cn.libreoffice.org/download/libreoffice/">...</a>
 */
@Configuration
public class OfficeConfig {

    private static final Logger logger = LoggerFactory.getLogger(OfficeConfig.class);

    @Bean(name = "OfficeManager")
    public OfficeManager officeManager() {
        logger.warn("=======> OfficeManager 开始初始化 <=======");
        OfficeManager officeManager = null;
        try {
            officeManager = LocalOfficeManager.builder()//
                    .officeHome(PathConstant.getOfficeHome())//
                    .install()//
                    .build();//
            // 启动 OfficeManager
            officeManager.start();
            logger.info("=======> OfficeManager 初始化成功 <=======");
            return officeManager;
        } catch (Exception e) {
            logger.error("OfficeManager 初始化失败：{}", e.getMessage(), e);
            // 如果officeManager已经创建但启动失败，确保资源被清理
            if (officeManager != null && officeManager.isRunning()) {
                try {
                    officeManager.stop();
                } catch (Exception stopEx) {
                    logger.warn("停止已启动的OfficeManager时发生异常：{}", stopEx.getMessage());
                }
            }
            throw new IllegalStateException("OfficeManager 初始化失败，无法启动应用", e);
        }
    }
}
